﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Red.Controls.Shell;
using Red.Core;

namespace Red.Controls
{
    public partial class CustomVariablePickerDialog : RedWindow
    {
        public static IEnumerable<IFilePathCustomVariable> Variables => FilePath.Variables;

        public IDictionary EnvironmentVars { get; private set; }

        public ICollectionView CustomVariablesView { get; private set; }
        public ICollectionView EnvironmentVarsView { get; private set; }

        public CustomVariablePickerDialog()
        {
            InitializeComponent();

            EnvironmentVars = Environment.GetEnvironmentVariables();

            CustomVariablesView = CollectionViewSource.GetDefaultView( Variables );
            CustomVariablesView.Filter = new Predicate<object>( Filter );

            EnvironmentVarsView = CollectionViewSource.GetDefaultView( EnvironmentVars );
            EnvironmentVarsView.Filter = new Predicate<object>( Filter );

            _customVariablesGrid.MouseDoubleClick += _customVariablesGrid_MouseDoubleClick;
            _envVarsGrid.MouseDoubleClick += _envVarsGrid_MouseDoubleClick;

            _filter.TextChanged += ( object sender, TextChangedEventArgs e ) => { CustomVariablesView.Refresh(); EnvironmentVarsView.Refresh(); };
        }

        private void InsertVariable( string variable, char delimiter )
        {
            _text.SelectedText = $"{delimiter}{variable}{delimiter}";
            _text.CaretIndex += _text.SelectedText.Length;
            _text.SelectionLength = 0;
        }

        private bool Filter( object obj )
        {
            string filterText = (obj as IFilePathCustomVariable)?.Name ?? (string)(((DictionaryEntry)obj).Key);

            if ( string.IsNullOrWhiteSpace( _filter.Text ) || filterText.ToLower().Contains( _filter.Text.ToLower() ) )
            {
                return true;
            }

            return false;
        }

        private void _envVarsGrid_MouseDoubleClick( object sender, MouseButtonEventArgs e )
        {
            DictionaryEntry envVar = (DictionaryEntry)_envVarsGrid.SelectedItem;

            InsertVariable( (string)envVar.Key, '%' );
        }

        private void _customVariablesGrid_MouseDoubleClick( object sender, MouseButtonEventArgs e )
        {
            IFilePathCustomVariable customVar = (IFilePathCustomVariable)_customVariablesGrid.SelectedItem;

            InsertVariable( customVar.Name, '$' );
        }
    }
}
